//
//  WBBaseViewController.swift
//  Weibo
//
//  Created by Albert Zhu on 16/9/28.
//  Copyright © 2016年 Albert Zhu. All rights reserved.
//

import UIKit

class WBBaseViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
   
    //MARK: - 属性
    /// 表格视图(用户没有登录就不创建)
    var tableView: UITableView?
    
    /// 刷新控件
    var refreshControl: WBRefreshControl?
    
    /// 上拉刷新标记
    var isPullup = false
    
    var visitorInfo: [String:String]?
    
    lazy var navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 64))
    
    lazy var navItem = UINavigationItem()
    
    override var title: String? {
        didSet{
            navItem.title = title
        }
    }

    
    //MARK: - 函数
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        WBNetworkManager.shared.userLogon ? loadData() : ()
        
        NotificationCenter.default.addObserver(self, selector: #selector(loginSuccess), name: NSNotification.Name(rawValue: WBUserLoginSucceedNotification), object: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    // MARK: 加载数据源方法
    func loadData() {
        refreshControl?.endRefreshing()
    }

    // MARK: UITableView代理方法
    func numberOfSections(in tableView: UITableView) -> Int {
        return 0
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        let section = tableView.numberOfSections - 1
        let row = tableView.numberOfRows(inSection: section) - 1
        
        if row == indexPath.row && !isPullup {
            
            isPullup = true
            
            loadData()
        }
    }
}


// MARK: - 按钮监听方法
extension WBBaseViewController {
    
    @objc func login() {
        debugPrint("login")
        
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
    }
    
    @objc func register() {
       debugPrint("register")
    }
    
    @objc func loginSuccess(noti: Notification) {
       debugPrint("登录成功----------\(noti)")
        
        // 设置控制器View为nil之后，控制器会重新执行loadView->viewDidLoad等方法
        view = nil
        navItem.leftBarButtonItem = nil
        navItem.rightBarButtonItem = nil
        
        NotificationCenter.default.removeObserver(self)
    }
}

// MARK: - UI设置
extension WBBaseViewController {
    
    /// 设置整个UI
    func setupUI() {
        view.backgroundColor = UIColor.white

        automaticallyAdjustsScrollViewInsets = false
        
        setupNavigationBar()
        
        WBNetworkManager.shared.userLogon ? setupTableView() : setupVisitorView()
    }
    
    /// 设置tableview
    func setupTableView() {
        
        tableView = UITableView(frame: view.bounds, style: .plain)
        tableView?.contentInset = UIEdgeInsets(top: navigationBar.bounds.height, left: 0, bottom: tabBarController?.tabBar.bounds.height ?? 49, right: 0)
        tableView?.scrollIndicatorInsets = tableView!.contentInset
        
        view.insertSubview(tableView!, belowSubview: navigationBar)
        
        // 设置数据源和代理
        tableView?.dataSource = self
        tableView?.delegate = self
        
        // 设置刷新控件
        refreshControl = WBRefreshControl()
        refreshControl?.addTarget(self, action: #selector(loadData), for: .valueChanged)
        tableView?.addSubview(refreshControl!)
    }
    
    /// 设置自定义导航栏
    private func setupNavigationBar() {
        view.addSubview(navigationBar)
        
        navigationBar.barTintColor = UIColor.az_RGBColor(red: 246, green: 246, blue: 246)
        navigationBar.tintColor = UIColor.orange
        navigationBar.items = [navItem]
        navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.darkGray]
    }
    
    /// 设置访客视图
    private func setupVisitorView() {
        let visitView = WBVisitorView(frame: view.bounds)

        view.insertSubview(visitView, belowSubview: navigationBar)
        
        visitView.visitorInfo = visitorInfo
        
        visitView.loginBtn.addTarget(self, action: #selector(login), for: .touchUpInside)
        visitView.registerBtn.addTarget(self, action: #selector(register), for: .touchUpInside)
        
        
        navItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: .plain, target: self, action: #selector(register))

        navItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: .plain, target: self, action: #selector(login))

    }
}
